package httpResp

import (
	"bytes"
	"gitee.com/igolang/imoney/internal/common/constants"
	"gitee.com/igolang/imoney/internal/common/entities"
	"gitee.com/igolang/pkg/xhttp"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
	"time"
)

type (
	DefaultResponse struct {
		Code        int    `json:"code"`
		Message     string `json:"msg"`
		CurrentTime int64  `json:"currentTime"`
		Data        any    `json:"data,omitempty"`
	}

	Resp DefaultResponse
)

func Response() (r *Resp) {
	r = new(Resp)
	r.Code = http.StatusOK
	return
}

func AbortJSON(ctx *gin.Context, r *Resp) {
	ctx.Abort()
	JSON(ctx, r)
}

func JSON(ctx *gin.Context, r *Resp) {
	if err := recover(); err != nil {
		panic(err)
	}

	if r.Message == "" {
		r.Message = getMsg(r.Code)
	}
	r.CurrentTime = time.Now().Unix()
	ctx.JSON(http.StatusOK, r)
	return
}

func Stream(ctx *gin.Context, w *bytes.Buffer) {
	ctx.Header(xhttp.HeaderContentType, xhttp.MIMEOctetStream)
	ctx.Header(xhttp.HeaderContentLength, cast.ToString(w.Len()))
	ctx.Status(http.StatusOK)
	ctx.Writer.WriteHeaderNow()
	ctx.Writer.Write(w.Bytes())
}

func Export(ctx *gin.Context, w *bytes.Buffer, blobType string) {
	export := &entities.Export{
		BlobType: blobType,
		Charset:  "utf-8",
		Buffer:   w,
	}
	ctx.Header(constants.ExportHeaderRespKey, constants.ExportHeaderRespValue)
	export.Stream(ctx)
}
